package com.gcsoftware.handler;

import com.gcsoftware.exception.GaffException;
import com.gcsoftware.web.response.ResultRsp;
import com.gcsoftware.web.utils.JsonUtils;
import com.gcsoftware.web.utils.ResultUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理类
 * Created by qs on 2018/4/5.
 */
@ControllerAdvice
public class GaffExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object handleBaseException(HttpServletRequest request, Exception exception) {
        if (exception instanceof GaffException) {
            GaffException e = (GaffException) exception;
            if(JsonUtils.isJson(request)) {
                return ResultUtils.error(e.getCode(),e.getMessage());
            } else {
                ModelAndView mview = new ModelAndView();
                mview.setViewName("error");
                mview.addObject("code",e.getCode());
                mview.addObject("message" , e.getMessage());
                return mview;
            }
        }else {
            if(JsonUtils.isJson(request)) {
                return ResultUtils.error(500,exception.getMessage());
            } else {
                ModelAndView mview = new ModelAndView();
                mview.setViewName("error");
                mview.addObject("code",500);
                mview.addObject("message" , exception.getMessage());
                return mview;
            }
        }

    }


}
